<?php
	/**
	 * explorer.php
	 * 
	 * unit which is called to create a directory listing of the
	 * directory passed in the parameter.
	 * 
	 * the GET "v" parameter must be set to the directory which should be displayed.
	 * if the parameter is empty or invalid explorer will display it's root directory
	 * 
	 * The get "openuploader" indicates if the uploader should be visible on document
	 * load. Value needs to be 1 in order for the uploader to show
     * 
     * @todo Separate application logic from HTML. Adopt some MVC pattern.
	 */
	
	session_start();
	
	require_once 'lib/dir.php';     // Unit for working with Directories
	require_once 'lib/file.php';    // Unit for working with Files
	require_once 'lib/common.php';  // Generic library for bitmanager
	
	require_once 'bmconfig.php';    // Import configuration
	
	if (!isLoggedIn())
	{
		header('Location: login.php');
		exit;
	}

	# In case a directory is not set we use the homedir
	$workingDir = (isset($_GET["v"]) && ($_GET["v"] != "")) ? getRelativePath(gpcSlashes($_GET["v"])) : HOMEDIR;
	
	
	# In case that even homedir doensn't exist we just display explorer.php's directory
	if (!file_exists($workingDir))
		$workingDir = '.';  
		
	if (!isAllowedView($workingDir))
	{        
		showFatalError('Forbidden', "You don't have permission to access '$workingDir' on this server");
		exit;
	}
	
	$d = new Dir(str_replace('\\', '/', realpath($workingDir)));   
	
	initSite("Directory Listing of {$d->getName()}", realpath($workingDir));
	
	$d->setFullPath($workingDir);
	
	# The mask being applied to files
	
	# filemask is the case-insensitive mask being applied
	$filemask = isset($_GET["mask"]) ? $_GET["mask"] : "*.*";
	
	# OriginalMask is the mask the user wrote
	$originalMask = $filemask == "*.*" ? "" : $filemask;
	
	$filemask = strtoupper($filemask);
	?>
		<script type="text/javascript"> 
		var searchDefTxt = "Filter files ...";

		function openUploadForm()
		{
			$("#upform").slideDown();
			$("#upform").data('isVisible', "1");
		}
		
		$(document).ready
		(
			function()
			{
				$("#msgdiv").hide();    // hiding message container
				$("#upform").hide();    // upload form
				$(".manager").hide();   // spans which contain the file functions
                
                document.getElementById('overwrite-ifexists').checked = true
				
				$("#bm_menu li input")
					.click
					(
						function ()
						{
							if ($(this).val() == searchDefTxt)
							{
								$(this).val("");
								$("#bm_menu li input").css('text-align', 'left');
							}
							else
								$(this).select();
						}
					)
					.blur
					(
						function ()
						{
							if ($(this).val() == "")
								{
									$(this).val(searchDefTxt);    
									$("#bm_menu li input")
										.css('color', 'gray')
										.css('text-align', 'center');
								}
						}
					)
					.keydown
					(
						function(e)
						{
							$("#bm_menu li input")
								.css('color', 'black')
								.css('text-align', 'left');
							
							if (e.keyCode == 13)
								pageRefresh(true);
						}
					).val(<?php echo isset($_GET["mask"]) ? '"' . $_GET["mask"] . '"' : "searchDefTxt" ?>)
					<?php if (isset($_GET["mask"])) echo ".click()" ?>
				
				<?php
				if (isset($_GET["openuploader"]) && ($_GET["openuploader"] == 1))
				{
					?>           
					openUploadForm();
					<?php
				}
				
				if (isset($_GET["mask"]))
				{
					echo "showCustomMsg(\"Currently applying <b>$originalMask</b> file mask. <a href='javascript:pageRefresh(false)'>Remove mask</a>\")";  
				}
				?>
				}
			);
		</script>
    <input type="hidden" id='currdir' value="<?php echo urlencode($workingDir) ?>">
    <?php include 'explorer-top-menu.php' ?>
	<div id="msgdiv" class="msg"></div> 
	<br>  
	
	<span class="filechecks">
		<a href="javascript:checkAll(true)" class="extra-ops">Check all</a>
		<a href="javascript:checkAll(false)" class="extra-ops">Uncheck all</a>
		<a href="javascript:invertSelection()" class="extra-ops">Invert selection</a>
	</span>

	<table id="main-tbl">
	<tr>
		<th>
			File name
		</th>
		<th class="filesize">
			File size
		</th>
		<th class="manage">
			Actions
		</th>
	</tr>
<?php 
	
	$f = new File("");

	# Tr classes '' is the default class, alt is the highlighted one
	$classes = ZEBRA_GRIDS ? array(false => "", true => "alt") : array(false=>"", true=>"");

	# boolean to determine usage of default or alternative class
	$alt = false;
	
	$fCnt    = 0;   # File count
	$dirCnt  = 0;   # Directory count
	$totalFs = 0;   # Total filesize
	
	foreach ($d->enumFiles() as $file)
	{   
		$f->setFullFilename($file);    
		
		# In case there is a file mask
		# and this file/folder doens't match it
		# continue to the next one
		if (($filemask !== "*.*") && (!fnmatch($filemask, strtoupper($f->getFilename()))))
			continue;
				
		
		# url-safe link to the file
		$safeUrl = base64_encode($file);
			
		$dir = is_dir($file);
		
		if (file_exists($file))
		{
			# If the current item is a file
			# increment the file count
			# and total filesize
			if (!$dir)
			{
				$fCnt++;
				$totalFs += $f->getSize();
			}
			else
			    # increment directory count
				$dirCnt++;   
				
			# inverting alt to get the alternate color for the table row
			$alt = !$alt;
			
			$rowNr = $fCnt + $dirCnt;
			
			?>  
			<tr <?php
					if ($classes[$alt] !="")
						echo "class='$classes[$alt]'";
				 ?> id="row<?php echo $rowNr?>">
				<td>
					<?php 
						# Checking if it's a directory or a file
						if ($dir)
						{
							$link = urlencode($file);
							?>
							<img src='img/folder16.png' alt='Folder icon'>
							<a class='filelist' title='Open this directory' href='explorer.php?v=<?php echo $link?>'><?php echo basename($file) ?></a>
								
							<?php
						}
						else
						{
							?>            
							<input type="checkbox" name="<?php echo $file ?>" style="vertical-align: middle;" id="file_cb<?php echo $rowNr ?>" value="<?php echo $safeUrl ?>">
							<?php echo imgFromFile($file) ?>
							<a class='filelist' title='Open this file' href='open.php?f=<?php echo $safeUrl?>'><?php echo $f->getFilename()?></a> 
							<?php       
						}
					?>
				</td>
				<td>
					<?php 
						if ($dir)
							echo "n/a";
						else
							echo intToFilesize($f->getSize());    
					?>
				</td>
				<td>
					<?php
						if (!$dir): ?>
<a class="fileops" title="Edit <?php echo $f->getFilename() ?>" href="editfile.php?f=<?php echo $safeUrl ?>">edit</a> 
	-
	
	<a class='fileops' title="Rename <?php echo $f->getFilename() ?>" href="javascript:renameFile(<?php echo "'$safeUrl', '" . addslashes($f->getFilename()) . "'" ?>)">rename</a> 
	-
	
	<a class='fileops' title="Delete <?php echo $f->getFilename() ?>" href="javascript:rmfile('<?php echo $safeUrl ."',$rowNr" ?>);">delete</a>
	-
	<a class='fileops' title="Download" href="manager.php?action=download&amp;f=<?php echo $safeUrl ?>">download</a>   
	-
	<a class='fileops' title="Download this file as a zip archive" href="manager.php?action=download&amp;zip=true&amp;f=<?php echo $safeUrl ?>">zip</a>   

                    <?php else: ?>
<a href="javascript:rmdir('<?php echo $safeUrl ."',$rowNr" ?>);">delete</a>
                    <?php endif; ?>
				</td>

			</tr>             
<?php    
		}
	}
?>
	<tr class="gray">
		<td>
			<?php echo "<span id='totalFiles'>$fCnt</span> files / <span id='totalFolders'>$dirCnt</span> folders"; ?>
		</td>
		<td>
			Total filesize <?php echo intToFileSize($totalFs) ?>
		</td>
		<td>
		</td>
	</tr>
</table>

<?php finishSite() ?>
